package cqrtplm.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ConvertExcelToPdfUtil {

    private static Font chineseFont;

    static {
        try {
            // 初始化中文字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            chineseFont = new Font(bfChinese, 10, Font.NORMAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ConvertExcelToPdfUtil(){
    }

    public ConvertExcelToPdfUtil(String excelPath, String pdfPath){
        convertExcelToPdf(excelPath, pdfPath);
    }

    public void convertExcelToPdf(String excelPath, String pdfPath) {
        try {
            // 1. 读取Excel文件
            FileInputStream excelFile = new FileInputStream(excelPath);
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet sheet = workbook.getSheetAt(0);
            // 2. 创建PDF文档
            Document document = new Document(PageSize.A4.rotate()); // 横向页面
            PdfWriter.getInstance(document, Files.newOutputStream(Paths.get(pdfPath)));
            document.open();
            // 3. 创建PDF表格（列数与Excel相同）
            PdfPTable pdfTable = new PdfPTable(sheet.getRow(0).getPhysicalNumberOfCells());
            pdfTable.setWidthPercentage(100); // 表格宽度100%
            // 4. 设置表格单元格属性
            PdfPCell cell;
            // 5. 遍历Excel行和单元格
            for (Row row : sheet) {
                for (Cell excelCell : row) {
                    // 获取单元格值（处理各种类型）
                    String cellValue = getCellValue(excelCell);
                    // 创建PDF单元格，应用中文字体
                    cell = new PdfPCell(new Phrase(cellValue, chineseFont));
                    // 设置单元格属性（可选）
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell.setPadding(5);
                    pdfTable.addCell(cell);
                }
            }
            // 6. 将表格添加到PDF文档
            document.add(pdfTable);
            document.close();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

}
